<template>
    <div class="common-page page-staff-work-order" v-loading.fullscreen="loading">
        <div class="common-page__head">
            <comp-paths class="route" :paths="['/staff/work', '/staff/work/orders/type1', $route.fullPath]"></comp-paths>
            <div class="title" v-if="order">
                <div class="text">{{ order.title }}</div>
                <div class="flag" v-for="tag in order.tags" :key="tag.id">{{ tag.name }}</div>
            </div>
            <div class="title" v-else></div>
        </div>
        <div class="common-page__body common-form" style="display: flex" v-if="order">
            <div class="rows" style="flex: 3 1 0; padding-right: 0">
                <div class="row row--head">
                    <div class="name">基本信息</div>
                    <div class="value"></div>
                </div>
                <div class="row row--3x">
                    <div class="name">
                        <span v-if="order.company.type === 'company'">企业</span>
                        <span v-else-if="order.company.type === 'project'">项目</span>
                        <span v-else-if="order.company.type === 'area'">园区</span>
                        <span>名称</span>
                    </div>
                    <div class="value">{{ order.company.name }}</div>
                </div>
                <div class="row row--3x">
                    <div class="name">事项标题</div>
                    <div class="value">{{ order.title }}</div>
                </div>
                <div class="row row--3x">
                    <div class="name">事项描述</div>
                    <div class="value" style="white-space: pre-wrap">{{ order.content }}</div>
                </div>
                <div class="row row--3x">
                    <div class="name">事项附件</div>
                    <div class="value">
                        <div style="padding: 1px 0">
                            <comp-files-viewer :files="order.files" v-if="order.files.length > 0"></comp-files-viewer>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="name">事项分类</div>
                    <div class="value">
                        <span class="text" v-for="tag in order.tags" :key="tag.id">{{ tag.name }}</span>
                    </div>
                </div>
                <div class="row">
                    <div class="name">事项层面</div>
                  <div class="value">
                    <div v-if="order.level == 1 ">县级</div>
                    <div v-else-if="order.level == 2 ">市级</div>
                    <div v-else-if="order.level == 3 ">自治区级</div>
                    <div v-else>
                      <span v-if="order.dept.county.id">县级</span>
                      <span v-else-if="order.dept.city.id">市级</span>
                      <span v-else-if="order.dept.province.id">自治区级</span>
                    </div>
                  </div>
                </div>
                <div class="row">
                    <div class="name">事项状态</div>
                    <div class="value">
                        <span class="el-status--info" v-if="order.status === 'created'"></span>
                        <span class="el-status--danger" v-else-if="order.status === 'published' || order.status === 'return'"></span>
                        <span class="el-status--warning" v-else-if="order.status === 'handling'"></span>
                        <span class="el-status--success" v-else-if="order.status === 'finished'"></span>
                        <span>{{ order.statusText }}</span>
                    </div>
                </div>
                <div class="row row--2x">
                    <div class="name">提交人</div>
                    <div class="value">
                        <span>{{ order.creator.name }}</span>
                        <span style="margin-left: 0.5em; color: #aaa">{{ order.creator.number }}</span>
                    </div>
                </div>
                <div class="row">
                    <div class="name">提交时间</div>
                    <div class="value">{{ order.createdAt }}</div>
                </div>
<!--                <div class="row row&#45;&#45;2x">-->
<!--                    <div class="name">负责工作队</div>-->
<!--                    <div class="value">-->
<!--                        <span>{{ order.hand.name }}</span>-->
<!--                    </div>-->
<!--                </div>-->
<!--                <div class="row">-->
<!--                    <div class="name">负责服务专员</div>-->
<!--                    <div class="value">-->
<!--                        <span>{{ order.handler.name }}</span>-->
<!--                        <span style="margin-left: 0.5em; color: #aaa">{{ order.handler.number }}</span>-->
<!--                    </div>-->
<!--                </div>-->
                <div class="row row--2x">
                    <div class="name">关注数量</div>
                    <div class="value">
                        <span class="text">{{ order.likes }}人</span>
                        <span class="button" @click="getOrderLikers()">查看</span>
                    </div>
                </div>
                <div class="row">
                    <div class="name">办结时间</div>
                    <div class="value">
                        <span>{{ order.finishedAt }}</span>
                    </div>
                </div>
                <div class="row row--2x">
                    <div class="name">评价人</div>
                    <div class="value">
                        <span>{{ order.evaluatedCreator.name }}</span>
                        <span style="margin-left: 0.5em; color: #aaa">{{ order.evaluatedCreator.number }}</span>
                    </div>
                </div>
                <div class="row">
                    <div class="name">评价打分</div>
                    <div class="value">
                        <span v-if="order.evaluated === 'yes'">{{ order.evaluatedStars }}分</span>
                    </div>
                </div>
                <div class="row row--3x">
                    <div class="name">评价内容</div>
                    <div class="value">
                        <span v-if="order.evaluated === 'yes'">{{ order.evaluatedContent }}</span>
                    </div>
                </div>
            </div>
            <div class="rows" style="flex: 2 1 0; flex-wrap: nowrap; flex-direction: column; padding-right: 0">
                <div class="row row--head">
                    <div class="name">处理过程信息</div>
                    <div class="value"></div>
                </div>
                <div class="row row--3x" style="flex: 1 1 0; overflow-x: hidden; overflow-y: auto">
                    <div class="value">
                        <comp-order-tracks :order="order"></comp-order-tracks>
                    </div>
                </div>
            </div>
        </div>
        <div class="common-page__foot" v-if="editing || evaluating">
            <el-button type="primary" size="small" icon="el-icon-check" @click="setOrder()" v-if="editing">编辑</el-button>
            <el-button type="primary" size="small" icon="el-icon-check" @click="setOrderEvaluated()" v-if="evaluating">评价</el-button>
        </div>
        <comp-dialog title="查看关注" width="60vw" height="80vh" ref="orderLiker">
            <comp-order-likers style="height: 100%" ref="orderLikerList" :orderId="orderId">
                <template #foot="scope">
                    <el-button type="plain" size="small" icon="el-icon-close" @click="getOrderLikers('end')">关闭</el-button>
                </template>
            </comp-order-likers>
        </comp-dialog>
        <comp-dialog title="编辑事项" ref="orderSetForm" @close="setOrder('end')">
            <el-form size="small" label-width="98px" style="margin-right: 20px" @submit.native.prevent v-if="orderSetForm">
              <el-form-item label="问题层级：" required>
                <el-select v-model="orderSetForm.level" style="width: 600px" placeholder="请选择" @change="setOrder('order-dept')">
                  <el-option key="1" label="区县级" value="1"></el-option>
                  <el-option key="2" label="市级" value="2"></el-option>
                  <el-option key="3" label="自治区级" value="3"></el-option>
                </el-select>
              </el-form-item>
                <el-form-item label="事项标题：" required>
                    <el-input type="textarea" v-model="orderSetForm.title" style="width: 600px" placeholder="请输入" :maxlength="100" :rows="2" resize="none" :readonly="loading" @change="setOrder('validate')"></el-input>
                </el-form-item>
                <el-form-item label="事项描述：" required>
                    <el-input type="textarea" v-model="orderSetForm.content" style="width: 600px" placeholder="请输入" :maxlength="1000" :rows="10" resize="none" :readonly="loading" @change="setOrder('validate')"></el-input>
                </el-form-item>
                <el-form-item label="事项分类：" required>
                    <div style="width: 600px">
                        <el-checkbox v-for="tag in tags" :key="tag.id" v-model="tag.selected" style="margin-right: 20px" :label="tag.name" :disabled="orderSetForm.tags.length >= 1 && !tag.selected" @change="setOrder('validate')"></el-checkbox>
                        <!-- <el-radio  v-for="tag in tags" :key="tag.id" v-model="tag.selected" :label="tag.name" @change="setOrder('validate')"></el-radio> -->
                          <!-- <el-radio-group v-model="tag.selected">
                                <el-radio v-for="tag in tags" :key="tag.id" :label="tag.id">{{tag.name}}</el-radio>
                                  <el-radio :label="3">备选项</el-radio>
                                    <el-radio :label="6">备选项</el-radio>
                                    <el-radio :label="9">备选项</el-radio>
                            </el-radio-group> -->
                    </div>
                </el-form-item>
                <el-form-item label="事项附件：">
                    <div style="width: 600px">
                        <el-tag style="margin: 0 10px 10px 0" v-for="(file, index) in orderSetForm.files" :key="index" disable-transitions closable @close="setOrder('order-file-delete', file)">{{ file.name }}</el-tag>
                    </div>
                    <el-button type="plain" icon="el-icon-plus" @click="setOrder('order-file-upload', 'image')">选择图片</el-button>
                    <el-button type="plain" icon="el-icon-plus" @click="setOrder('order-file-upload', 'document')">选择文档</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-check" @click="setOrder('submit')">保存</el-button>
                    <el-button type="plain" icon="el-icon-close" @click="setOrder('end')">放弃</el-button>
                </el-form-item>
            </el-form>
        </comp-dialog>
        <comp-dialog title="评价事项" ref="orderEvaluatedSetForm" @close="setOrderEvaluated('end')">
            <el-form size="small" label-width="98px" style="margin-right: 20px" @submit.native.prevent v-if="orderEvaluatedSetForm">
                <el-form-item label="评价打分：" required>
                    <el-select v-model="orderEvaluatedSetForm.evaluatedStars" style="width: 360px" placeholder="请选择" @change="setOrderEvaluated('validate')">
                        <el-option v-for="data in stars" :key="data.value" :label="data.name" :value="data.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="评价内容：" required>
                    <el-input type="textarea" v-model="orderEvaluatedSetForm.evaluatedContent" style="width: 360px" placeholder="请输入" :maxlength="1000" :rows="10" resize="none" :readonly="loading" @change="setOrderEvaluated('validate')"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-check" @click="setOrderEvaluated('submit')">提交</el-button>
                    <el-button type="plain" icon="el-icon-close" @click="setOrderEvaluated('end')">取消</el-button>
                </el-form-item>
            </el-form>
        </comp-dialog>
    </div>
</template>

<script>
    import mixin from "../mixin";
    import { string, int, deepCopy, selectFile, cache } from "../util";
    export default {
        name: "page-staff-work-order",
        title: "事项详情",
        nodes: ["/menu/staff-work"],
        childs: [],
        mixins: [mixin],
        data: () => ({
            loading: false,
            orderId: "",
            order: null,
            editing: false,
            evaluating: false,
            orderSetForm: null,
            orderEvaluatedSetForm: null,
            stars: [
                { name: "1分", value: 1 },
                { name: "2分", value: 2 },
                { name: "3分", value: 3 },
                { name: "4分", value: 4 },
                { name: "5分", value: 5 },
            ],
            tags: [],
        }),
        methods: {
            getOrderLikers(action, data) {
                if (this.loading) return;
                if (!action || action === "start") {
                    this.$refs.orderLiker.init();
                    this.$nextTick(() => this.$refs.orderLikerList.init());
                } else if (action === "end") {
                    this.$refs.orderLiker.close();
                }
            },
            uploadFile(type, file, callback) {
                if (this.loading) return;
                if (type && file) {
                    let timer = null;
                    let progress = (event) => timer = clearTimeout(timer) || setTimeout(() => this.plugins.modal.toast("上传进度：" + event.percent + "%", "info"), 200);
                    this.loading = true;
                    this.plugins.user.uploadFile(file, type, progress).then((res) => {
                        this.loading = false;
                        if (res.code === 0) string(() => callback(res.data));
                        else this.plugins.modal.alert("上传失败", res.code + "：" + res.msg, "error");
                    });
                } else if (type === "image") {
                    selectFile("image/*").then((file) => {
                        if (file.size > 5 * 1048576) this.plugins.modal.toast("图片过大，不能大于5MB哦！请重新选择。", "error");
                        else this.uploadFile(type, file, callback);
                    });
                } else if (type === "document") {
                    selectFile(".xls,.xlsx,.doc,.docx,.pdf").then((file) => {
                        if (file.size > 10 * 1048576) this.plugins.modal.toast("文档过大，不能大于10MB哦！请重新选择。", "error");
                        else this.uploadFile(type, file, callback);
                    });
                }
            },
            setOrder(action, data) {
                if (this.loading) return;
                let order = this.order;
                let form = this.orderSetForm;
                let tags = this.tags;
                if (action === "start" || !action) {
                    this.loading = true;
                    this.plugins.user.call(async () => {
                        if (tags.length > 0) { }
                        else tags = await this.plugins.user.getOrderOfTags().then((res) => res.code === 0 ? res.data : []);
                        return { code: 0 };
                    }).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.orderSetForm = form = deepCopy(order);
                            this.tags = tags;
                            this.tags.forEach((tag) => tag.selected = form.tags.map((tag) => tag.id).includes(tag.id));
                            this.setOrder("validate");
                            this.$refs.orderSetForm.init();
                        } else {
                            this.plugins.modal.toast("加载失败<br>" + res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "validate") {
                    let error = "";
                    form.title = string(form.title).trim();
                    error = error || (form.title ? "" : "请先输入事项标题！");
                    form.content = string(form.content).trim();
                    error = error || (form.content ? "" : "请先输入事项描述！");
                    form.tags = tags.filter((tag) => tag.selected);
                    // error = error || (form.tags.length <= 3 ? "" : "事项分类最多能选1个！");
                    error = error || (form.tags.length == 1 ? "" : "事项分类必填！");
                    form.level = string(form.level).trim();
                    error = error || (form.level ? "" : "请先选择问题层级！");
                    if (data) this.plugins.modal.toast(error, "error");
                    return !error;
                } else if (action === "order-file-upload") {
                    let type = data;
                    if (type) this.uploadFile(type, null, (file) => {
                        form.files.push(file);
                        this.setOrder("validate");
                    });
                } else if (action === "order-file-delete") {
                    let file = data;
                    let index = form.files.indexOf(file);
                    if (index > -1) form.files.splice(index, 1);
                } else if (action === "submit") {
                    if (!this.setOrder("validate", true)) return;
                    this.loading = true;
                    this.plugins.user.setOrder(form).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("保存成功！", "success");
                            this.setOrder("end");
                            this.init();
                        } else {
                            this.plugins.modal.alert("保存失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.orderSetForm.close();
                }
            },
            setOrderEvaluated(action, data) {
                if (this.loading) return;
                let order = this.order;
                let form = this.orderEvaluatedSetForm;
                if (action === "start" || !action) {
                    this.orderEvaluatedSetForm = deepCopy(order);
                    this.setOrderEvaluated("validate");
                    this.$refs.orderEvaluatedSetForm.init();
                } else if (action === "validate") {
                    let error = "";
                    form.evaluatedStars = Math.min(Math.max(int(form.evaluatedStars), 0), 5) || null;
                    error = error || (form.evaluatedStars > 0 ? "" : "请先选择评价打分！");
                    form.evaluatedContent = string(form.evaluatedContent).trim();
                    error = error || (form.evaluatedContent ? "" : "请先输入评价内容！");
                    if (data) this.plugins.modal.toast(error, "error");
                    return !error;
                } else if (action === "submit") {
                    if (!this.setOrderEvaluated("validate", true)) return;
                    this.loading = true;
                    this.plugins.user.setOrderEvaluated(form).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("提交成功！", "success");
                            this.setOrderEvaluated("end");
                            this.init();
                        } else {
                            this.plugins.modal.alert("提交失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.orderEvaluatedSetForm.close();
                }
            },
            destroy() {
                if (this.loading) return;
                return true;
            },
            init() {
                if (this.loading) return;
                let query = this.$route.query;
                let order = null;
                this.loading = true;
                this.orderId = query.orderId;
                this.order = cache(query.orderId);
                this.$root.$refs.navbar.init();
                this.plugins.user.call(async () => {
                    let res = await this.plugins.user.init();
                    if (res.code === 0) { }
                    return res;
                }, async () => {
                    if (this.access(this.$route.name)) return { code: 0 };
                    return this.env.xhrErrors.find((error) => error.code === 4);
                }, async () => {
                    let res = await this.plugins.user.getOrder(query.orderId);
                    if (res.code === 0) order = res.data;
                    if (res.code === 0) {
                        for (let track of order.tracks) {
                            let handler = track.handler;
                            let depments = handler.depments.splice(0);
                            for (let depment of depments) depment.dept.id === track.dept.id && handler.depments.push(depment);
                            let creator = order.creator;
                            let matched = track.type === "start" && track.handler.id === creator.id && creator.role === "holder";
                            if (matched) order.creator = track.handler;
                        }
                        for (let creator of [order.creator, order.evaluatedCreator]) {
                            let employees = creator.employees.splice(0);
                            for (let employee of employees) employee.company.id === order.company.id && creator.employees.push(employee);
                        }
                    }
                    return res;
                }).then((res) => {
                    this.loading = false;
                    this.$root.$refs.navbar.init();
                    if (res.code === 0) {
                        this.order = cache(query.orderId, order);
                        console.log(this.order);
                        this.editing = (order.status === "return" || order.status === "published") && this.profile.role === "staff" && this.profile.employees.some((employee) => employee.company.id === order.company.id);
                        this.evaluating = order.status === "finished" && order.evaluated === "not" && this.profile.role === "staff" && this.profile.employees.some((employee) => employee.company.id === order.company.id);
                    } else if (res.code === 2) {
                        this.$root.$refs.navbar.login();
                    } else {
                        this.plugins.modal.alert("页面加载失败", res.code + "：" + res.msg, "error").then(() => this.$router.replace("/staff/work/orders/type1"));
                    }
                });
            },
        },
    };
</script>

<style lang="scss">
    .page-staff-work-order {
        overflow: hidden;
    }
</style>